
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public final class Video2Mp3 {
	public static String toMp3(String inputPath, String outputBase, boolean deleteSrc) {
		File outputFile = new File(outputBase + ".mp3");
		String command = System.getProperty("os.name").toUpperCase().startsWith("WINDOWS") 
				? String.format("ffmpeg.exe -y -i \"%s\" -ar 44100 -ab 192000 \"%s\"", inputPath, outputFile.getPath())
				: String.format("ffmpeg -y -i %s -ar 44100 -ab 192000 %s", inputPath, outputFile.getPath());

		System.out.println(command);
		
		Runtime runtime = Runtime.getRuntime();
		Process process = null;
		try {
			process = runtime.exec(command);
			StreamGobbler err = new StreamGobbler(process.getErrorStream()); 
			StreamGobbler out= new StreamGobbler(process.getInputStream());
            err.start();  
            out.start();  
            
			int exitCode = process.waitFor();
			if (exitCode == 0) {
				return outputFile.getName();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
			if (process != null && process.getOutputStream() != null) {
				try {
					process.getOutputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (deleteSrc) {
				new File(inputPath).delete();
			}
		}

		return "";
	}
	
	public static void main(String[] args) {
		System.out.println(toMp3("/home/ytbdown/upload/1.flv", "/home/ytbdown/upload/1", false));
	}
	
	private static class StreamGobbler extends Thread {
		private InputStream is;

		public StreamGobbler(InputStream is) {
			this.is = is;
		}

		public void run() {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			try {
				while (br.readLine() != null);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					isr.close();
					br.close();
					this.is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}


